# _*_ encoding:utf-8 _*_
from django.contrib.auth.hashers import make_password

from rest_framework import serializers

from users.models import User


class UserModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = [
            'id',
            'username',
            'mobile',
            'email',
        ]

        # 修改字段约束 -->  write_onl=True 表示只参与反序列化
        extra_kwargs = {
            'password': {'write_only': True, 'min_length': 8, 'max_length': 20},
            'username': {'min_length': 3, 'max_length': 20}
        }

    def validate(self, attrs):

        attrs['is_staff'] = True
        raw_password = attrs.get('password')  # 明文密码
        attrs['password'] = make_password(raw_password)  # 密文密码

        return attrs
